import json, os, pickle, sys

from uuid import UUID

from PyQt5.QtGui import QPixmap

config = {}
database = {}
cache: dict[UUID, QPixmap] = {}

def start(config_path: os.PathLike):
    global config, database

    print('Preparing to process music repository')

    with open(config_path) as f:
        config = json.load(f)

    if not os.path.exists(config['files']['audio']['path']):
        os.makedirs(config['files']['audio']['path'])

    if os.path.exists(config['files']['database']):
        with open(config['files']['database'], 'rb') as f:
            database = pickle.load(f)
        if database['format'] != 1:
            print('Database format incompatible')
            sys.exit(1)
    else:
        database = {
            'type': 'main',
            'music': {},
            'artists': {},
            'albums': {},
            'genres': {},
            'covers': {}
        }

def stop():
    global config, database

    print('Dumping database')
    with open(config['files']['database'], 'wb') as f:
        pickle.dump(database, f)

def get_cover(uuid: UUID):
    if not uuid in cache:
        print('Loading cover %s' % uuid)
        cache[uuid] = QPixmap(os.path.join(config['files']['images']['path'] if config['files']['images']['path'] else config['files']['audio']['path'], database['covers'][uuid]['path']))
    return cache[uuid]
